# 测试连接mqtt服务器
# 服务器: mq.wardyan.top
# 用户名: jkkdvece
# 密码: w_x1W8gI8Fq5wRDfUvAJ1bZz17qzMoVW
import paho.mqtt.client as mqtt
import zlib

# 服务器地址
broker_address = "mq.wardyan.top"
# 用户名
username = "jkkdvece:jkkdvece"
# 密码
password = "w_x1W8gI8Fq5wRDfUvAJ1bZz17qzMoVW"

# 创建MQTT客户端实例
client = mqtt.Client()

# 设置用户名和密码
client.username_pw_set(username, password)
def on_message(client, userdata, msg):
    #print(f"收到消息: {msg.payload} 从主题: {msg.topic}")
    try:
        # 解压 zlib 压缩的数据
        decompressed_data = zlib.decompress(msg.payload)
        # 将解压后的 bytes 转换为字符串（假设原始文本是 UTF-8 编码）
        payload_str = decompressed_data.decode('utf-8')
        print("长度:", len(msg.payload) / 1024, "KB")
        print(f"收到消息: {payload_str} 从主题: {msg.topic}")
    except zlib.error as e:
        print(f"zlib 解压失败: {e}，原始数据为: {msg.payload}")
    except UnicodeDecodeError:
        print(f"解压成功，但无法解码为 UTF-8 字符串。原始解压数据为: {decompressed_data}")

# 定义连接回调函数
def on_connect(client, userdata, flags, rc):
    if rc == 0:
        print("成功连接到MQTT服务器")
        # 连接成功后发送消息
        #topic = "queue/test"
        topic = "checktoolserver"
        #message = "Hello, MQTT Queue!"
        #message = "A" * 20000  # 生成包含2万个'A'的消息

        client.subscribe(topic)

        # client.publish(topic, message)
        # print(f"消息已发送到主题: {topic}")
    else:
        print(f"连接失败，返回码: {rc}")
# 将连接回调函数分配给客户端
client.on_connect = on_connect

# 连接到MQTT代理
client.connect(broker_address)
# 将消息回调函数分配给客户端
client.on_message = on_message

# 启动网络循环
client.loop_start()

# 保持程序运行一段时间以便查看连接结果
import time
while True :
    time.sleep(50)

# 停止网络循环
client.loop_stop()